import { getCliInfo, updateCliInfo } from '../../../services/usercenter/index';
import Message from 'tdesign-miniprogram/message/index';


Page({
  data: {
    defaultAvatarUrl: '/assets/avatart/default-avatar.png',
    personInfo: {
      avatarUrl: '',
      nickName: '',
      gender: '',
      phone: '',
      email: '',
    },
    loading: true,
    canIUseGetUserProfile: wx.canIUse('getUserProfile'),
    canIUseNicknameComp: wx.canIUse('input.type.nickname'),
    showUnbindConfirm: false,
    genderOptions: [
      { value: '0', label: '男' },
      { value: '1', label: '女' },
      { value: '2', label: '未知' },
    ],
  },
  onLoad() {
    this.init();
  },
  init() {
    this.loadUserProfile();
  },
  loadUserProfile() {
    this.setData({ loading: true });
    const personInfo = wx.getStorageSync('userInfo');
    if (personInfo) {
      this.setData({ personInfo })
    } else {
      const _this = this;
      getCliInfo().then(res => {
        console.log(res);
        const personInfo = res.data;
        wx.setStorageSync('userInfo', personInfo)
        _this.setData({ personInfo });
      })
    }
    this.setData({ loading: false });
  },
  onChooseAvatar(e) {
    const { avatarUrl } = e.detail
    const defaultAvatarUrl = this.data.defaultAvatarUrl;
    const { nickName } = this.data.personInfo
    console.log('onChooseAvatar', avatarUrl, nickName)
    this.setData({
      "personInfo.avatarUrl": avatarUrl,
      hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
    })
  },
  // 修改性别
  handleGenderChange(e) {
    this.setData({
      'personInfo.gender': e.detail.value
    });
  },
  handleNickNameChange(e) {
    const nickName = e.detail.value
    this.setData({
      "personInfo.nickName": nickName,
    })
  },
  handleEmailInput(e) {
    const email = e.detail.value
    this.setData({
      "personInfo.email": email,
    })
  },
  handlePhoneInput(e) {
    const phone = e.detail.value
    this.setData({
      "personInfo.phone": phone,
    })
  },
  submit() {
    this.setData({ loading: true });
    const _this = this
    let info = this.data.personInfo;
    info.avatarUrl = null;
    updateCliInfo(info).then(res => {
      if (res.code === 200) {
        getCliInfo().then(res => {
          const personInfo = res.data;
          wx.setStorageSync('userInfo', personInfo)
        })
        wx.navigateBack({ backRefresh: true });
      } else if (res.error) {
        console.error(res.error)
        Message.error({
          context: _this,
          offset: [45, 32],
          content: '更新错误: ' + res.error,
        })
      }
    })
    this.setData({ loading: false });
  },
})